package com.fan.shop.businesslogic;

import java.io.File;

import org.apache.log4j.Logger;

import com.fan.shop.domain.Brand;
import com.fan.shop.global.ShopGlobalVariables;
import com.fan.shop.process.ProcExec;
import com.fan.shop.services.BrandService;

public class BrandUpdateProcess extends ProcExec<Integer> {

	private static Logger logger = Logger.getLogger(BrandUpdateProcess.class);
	private Brand brand;
	private BrandService brandService;
	private File iconTempFile;

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		BrandUpdateProcess.logger = logger;
	}

	public Brand getBrand() {
		return brand;
	}

	public void setBrand(Brand brand) {
		this.brand = brand;
	}

	public BrandService getBrandService() {
		return brandService;
	}

	public void setBrandService(BrandService brandService) {
		this.brandService = brandService;
	}

	public File getIconTempFile() {
		return iconTempFile;
	}

	public void setIconTempFile(File iconTempFile) {
		this.iconTempFile = iconTempFile;
	}

	private String saveIconFile() {
		FileSaveProcess fileSaveProcess = new FileSaveProcess();
		fileSaveProcess.setFile(iconTempFile);
		fileSaveProcess.setUploadType(ShopGlobalVariables.BRAND_ICON);
		fileSaveProcess.setFileName(brand.getName());
		int result = fileSaveProcess.process();

		if (result == ShopGlobalVariables.SUCCESS) {
			return fileSaveProcess.getRelativePath();
		} else {
			return null;
		}
	}

	@Override
	public Integer processImpl() {
		if (brand == null) {
			setErrorMessage("Brand is null!");
			return ShopGlobalVariables.FAILED;
		}
		if (!brandService.hasBrand(brand.getName())) {
			setErrorMessage("Brand" + brand.getName() + " doesn't exist!");
			return ShopGlobalVariables.FAILED;
		} else {

			try {
				String iconFilePath = saveIconFile();
				if (iconFilePath != null) {
					brand.setIcon(iconFilePath);
				}
				brandService.updateStock(brand);
			} catch (Exception e) {
				setErrorMessage(e.getMessage());
				e.printStackTrace();
				return ShopGlobalVariables.FAILED;
			}
			return ShopGlobalVariables.SUCCESS;
		}

	}

}
